//
// Created by Luhang on 2023/10/11/011.
//
//项目实用类
//获取系统时间，判断文件是否存在，获取文件的所在目录路径，创建目录

#ifndef LOGPROJECT_UTIL_H
#define LOGPROJECT_UTIL_H

#include <iostream>
#include <string>
#include <ctime>
#include <cassert>
#include <sys/stat.h>
#include <sys/types.h>
#include <fstream>
#include <sstream>

namespace LuLog{
    namespace util{
        class Date{
        public:
            static size_t now(){
                return time(nullptr);
            }
        };

        class File{
        public:
            static bool exists(const std::string &name){
                //只适用于linux
                //return access(name.c_str(), F_OK) == 0;
                //适用于Linux or Windows
                struct stat st{};
                return stat(name.c_str(), &st) == 0;
            }

            static std::string path(const std::string &name){
                if(name.empty())
                    return ".";
                //从最后查找/ \ 任意字符
                size_t pos = name.find_last_of("/\\");
                if(pos == std::string::npos)
                    return ".";//查不到则返回当前目录
                return name.substr(0, pos + 1);//包含/在内
            }

            static void createDirectory(const std::string &path){
                if(path.empty())
                    return;
                if(exists(path))
                    return;
                size_t pos, index = 0;
                while (index < path.size()){
                    pos = path.find_first_of("/\\", index);
                    if(pos == std::string::npos){
                        //C++接口
                        //mkdir(path.c_str());
                        mkdir(path.c_str(), 0777);
                        return;
                    }
                    std::string parent_dir = path.substr(0, pos + 1);
                    //该目录已经存在
                    if(exists(parent_dir)){
                        index = pos + 1;
                        continue;
                    }
                    //mkdir(parent_dir.c_str());
                    mkdir(parent_dir.c_str(), 0777);
                    index = pos + 1;
                }
            }
        };
    }
}


#endif //LOGPROJECT_UTIL_H

